#include "wl_net.h"
#include "wl_malloc.h"
#include "wl_trace.h"
#include "wl_core.h"

wl_int32 wl_ext_net_process_message(wl_task_message* message) {
    wl_ext_net_message net_message;
    if (message == NULL || sizeof(wl_ext_net_message) != message->datalen) {
        WLLOGW("message is null");
        return -1;
    }

    memcpy(&net_message, &(message->data), message->datalen);
    if (net_message.pContext) {
        ((wl_ext_tcp_callback)net_message.pContext)(net_message.handle, net_message.tcp_event, NULL);
    }

    return 0;
}


void wl_ext_network_callback_wrapper(wl_ext_tcp_handle handle, int tcp_event, void* context) {
    wl_task_message message;
    wl_ext_net_message net_message;

    memset(&message, 0, sizeof(wl_task_message));
    memset(&net_message, 0, sizeof(wl_ext_net_message));

    net_message.handle = handle;
    net_message.tcp_event = tcp_event;
    net_message.pContext = context;

    message.type = WL_TASK_MSG_NET;
    memcpy(&message.data, &net_message, sizeof(wl_ext_net_message));
    message.datalen = sizeof(wl_ext_net_message);

    wl_send_task_message(WL_TASK_APP, &message);
}

wl_int32 wl_http_process_message(wl_task_message* message) {
    wl_ext_http_message *http_message;
    if (message == NULL || sizeof(wl_ext_http_message *) != message->datalen) {
        WLLOGW("message is null");
        return -1;
    }

    memcpy(&http_message, message->data, message->datalen);

    WLLOGD("status %d dataLen %d", http_message->status, http_message->dataLen);

    if (http_message->callback) {
        ((wl_ext_http_callback)http_message->callback)(http_message->handle, http_message->status, http_message->data, http_message->dataLen);
    }
    
    wl_free(http_message);

    return 0;
};
